<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card 内容区 -->
    <el-card>
      <!-- 警告区 -->
      <el-alert
        title="注意：只有商品三级分类可选"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="cateCateKeys"
            :options="catelist"
            :props="CateCascaderProps"
            @change="cateCascaderChange"
          >
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tabs页签区 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtrnDisable"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 表格展示数据 -->
          <el-table :data="manyTableData" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 展示tags -->
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!--添加按钮和输入框的动态切换展示 elementui有 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ 新标签</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtrnDisable"
            @click="addDialogVisible = true"
            >添加属性
          </el-button>
          <!-- 表格展示数据 -->
          <el-table :data="onlyTableData" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 展示tags -->
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!--添加按钮和输入框的动态切换展示 elementui有 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ 新标签</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添动态参数或者添加静态属性对话框 -->

    <el-dialog
      :title="titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!--添加表单区  -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label-width="120px" :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="titleText"
      :visible.sync="editDialog"
      width="50%"
      @close="editDialogClosed"
    >
      <!--添加表单区  -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label-width="120px" :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表 级联选择器的绑定显示的数据
      catelist: [],
      //   级联选择器选中的数据数组
      cateCateKeys: [],
      //级联选择器的配置对象
      CateCascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },
      // tabs绑定的数据 页签项的name
      activeName: 'many',
      //   参数数据
      manyTableData: [],
      //   静态属性数据
      onlyTableData: [],
      //   添加参数或者属性
      addDialogVisible: false,
      editDialog: false,
      // 添加的表单
      addForm: {
        attr_name: '',
      },
      // 验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '不为空', trigger: 'blur' }],
      },

      // 修改的表单数据
      editForm: {
        attr_name: '',
      },
      //验证规则
      editFormRules: {
        attr_name: [{ required: true, message: '不为空', trigger: 'blur' }],
      },
 

    }
  },
  computed: {
    // 按钮是否被禁用
    isBtrnDisable() {
      if (this.cateCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级分类的id
    cateId() {
      if (this.cateCateKeys.length === 3) {
        // 取出选中的最后一项的id值
        return this.cateCateKeys[2]
      }
      return null
    },
    //对话框标题
    titleText() {
      if (this.activeName === 'many') {
        return '添加动态参数'
      }
      return '添加静态属性'
    },
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取商品分类列表失败')
      this.catelist = res.data
    },
    // 数据变化
    cateCascaderChange() {
      this.getParams()
    },
    //tabs 点击
    handleTabsClick() {
      this.getParams()

      //   console.log(this.activeName)
    },
    async getParams() {
      //  选择范围  不是第三级的  清空选中数据
      if (this.cateCateKeys.length !== 3) {
        this.cateCateKeys = []
        // 清空表格数据 
        this.onlyTableData=[]
        this.manyTableData=[]
        return
      }

      //获取数据  数据发生变化立即请求数据 默认是many数据

      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      //   字符串 转化成数组 为啦能for循环展示出tag
      res.data.forEach((item) => {
        // 是否是为空
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 为每个标签 添加自己的 显示状态和值
        item.inputVisible=false
        item.inputValue=''
      })

      console.log(res.data)
      //   判断是哪个页签的数据 分别赋值
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 关闭对话框重置数据
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 对话框 确定提交 接口一样 只是提交的参数不同
    addParams() {
      // 1，预验证
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: this.activeName }
        )
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        this.addDialogVisible = false
        this.getParams()
      })
    },

    // 显示修改对话框
    async showEditDialog(attr_id) {
      // 数据的回传显示
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200)
        return this.$message.error('获取参数数据失败')
      this.editForm = res.data
      this.editDialog = true
    },
    // 修改对话框关闭
    editDialogClosed() {
      this.editForm = {}
      this.$refs.editFormRef.resetFields()
    },
    //   确认修改后的提交
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        )
        if (res.meta.status !== 200)
          return this.$message.error('修改参数数据失败')
        this.$message.success('修改参数成功')
        this.getParams()
        this.editDialog = false
      })
    },
    // 删除参数
    async removeParams(attr_id) {
      // console.log('111');
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      // console.log('确认删除');
      // 删除业务逻辑
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200)
        return this.$message.error('删除参数数据失败')
      this.$message.success('删除参数成功')
      this.getParams()
    },
    // 添加标签的input回调函数  input 失去焦点 enter
    handleInputConfirm(row){
      // 优化 空字符 清空数据 不做操作
      if( row.inputValue.trim().length===0){
        row.inputValue=''
           // 切换到按钮
           row.inputVisible=false
        return 
      }
      // 输入内容合法
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue=''
        // 切换到按钮
        row.inputVisible=false
        // 需要发起请求 ，保存这次操作
       this.saveAttrVals(row)
    },
    // 展示输入框
    showInput(row){
     row.inputVisible=true
    //$nextTick  页面重新渲染之后再执行
    // 改过变量Dom 不是立即出现的
     this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    // 保存row.attr_vals 的修改到后端
    async saveAttrVals(row){
      const{data:res}=  await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
    {
      attr_name :row.attr_name,
      attr_sel:row.attr_sel,
      attr_vals:row.attr_vals.join(',')
    })
    if (res.meta.status !== 200)
          return this.$message.error('修改参数数据失败')
        this.$message.success('修改参数成功')
    },
    // 删除tag
    handleClose(i,row){
      row.attr_vals.splice(i,1)
      this.saveAttrVals(row)
    
    }
  

  },
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 0 15px;
}
.input-new-tag{
width: 120px;
}
</style>